package com.demo.widget.meis;

import com.demo.widget.ResourceTable;
import com.demo.widget.meis.video.VideoPlayerPlugin;
import com.meis.widget.photodrag.DragRelativeLayout;
import com.meis.widget.photodrag.OnDragListener;
import cs.help.tool.Log;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.*;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.window.service.WindowManager;
import ohos.media.common.AVDescription;
import ohos.media.common.sessioncore.AVElement;
import ohos.utils.net.Uri;

import java.util.Arrays;

/**
 * Created by wenshi on 2018/5/24.
 * Description
 */
public class MeiVideoDragFragment extends Fraction implements Component.ClickedListener {
    DragRelativeLayout mDragLayout;
    DependentLayout playVideo;
    Component titleShow;
    Component mIvClose;
    Image mIvBg;
    AnimalListener animalListener;
    int tag;
    private SurfaceProvider surfaceProvider;
    private Surface surface;
    private VideoPlayerPlugin videoPlayerPlugin;
    //防止suface重复创建导致播放问题
    private boolean isCreateSuface = false;

    public MeiVideoDragFragment(int tag) {
        this.tag = tag;
    }


    public AnimalListener getAnimalListener() {
        return animalListener;
    }

    public void setAnimalListener(AnimalListener animalListener) {
        this.animalListener = animalListener;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        mDragLayout = (DragRelativeLayout) scatter
                .parse(ResourceTable.Layout_mei_video_drag_fraction, container, false);
        titleShow = mDragLayout.findComponentById(ResourceTable.Id_title_show);
        playVideo = (DependentLayout) mDragLayout.findComponentById(ResourceTable.Id_play_video);
        mIvBg = (Image) mDragLayout.findComponentById(ResourceTable.Id_iv_bg);
        mIvClose = mDragLayout.findComponentById(ResourceTable.Id_iv_close);
        mIvClose.setClickedListener(this);
        mIvBg.setPixelMap(ResourceTable.Media_ic_video_drag_bg);
        mDragLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
            }
        });
        return mDragLayout;
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_iv_close:
                if (animalListener != null) {
                    animalListener.animalEnd();
                }
                if (videoPlayerPlugin != null)
                    videoPlayerPlugin.release();
                break;
        }
    }

    public void initPlay(int i) {
        if (tag == i) {
            playVideo();
        } else {
            if (mDragLayout != null) {
                mDragLayout.setTranslation(0, 0);
                mDragLayout.setScale(1, 1);
                notifyDataSetChanged();
            }
            if (videoPlayerPlugin != null && videoPlayerPlugin.isPlay()) {
                Log.i("MeiVideoDragFragment.onEndExit([]):199  videoPlayerPlugin:" + videoPlayerPlugin + "   pausePlay:" + tag);
                videoPlayerPlugin.pausePlay();
            }
        }
    }

    /**
     * SurfaceCallBack
     */
    class SurfaceCallBack implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps callbackSurfaceOps) {
            if (surfaceProvider.getSurfaceOps().isPresent()) {
                surface = surfaceProvider.getSurfaceOps().get().getSurface();
                Log.i("SurfaceCallBack.surfaceCreated([callbackSurfaceOps]):120   play");
                isCreateSuface = false;
                playVideo();
            }
        }

        @Override
        public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
        }
    }

    public void notifyDataSetChanged() {
        IntentParams intentParams = null;
        if (getFractionAbility() != null) {
            intentParams = getFractionAbility().getIntent().getParams();
        }
        if (intentParams != null) {
            int index = (int) intentParams.getParam("index");
            int[] loc = (int[]) intentParams.getParam("region");
            if (loc == null || mDragLayout == null) {
                return;
            }
            mDragLayout.setTransitionsRegion(loc[0], loc[1], loc[2], loc[3], loc[4], loc[5]);
            if (index == tag) {
                mDragLayout.startTransitions();
            }
        }
    }

    @Override
    protected void onStart(Intent intent) {
        notifyDataSetChanged();
        mDragLayout.setOnoDragListener(new OnDragListener() {
            @Override
            public void onStartDrag() {
                super.onStartDrag();
                titleShow.setVisibility(Component.HIDE);
                mIvClose.setVisibility(Component.HIDE);
            }

            @Override
            public void onStartEnter(boolean outOfBound) {
                super.onStartEnter(outOfBound);
                playVideo();
            }

            @Override
            public void onRelease(boolean isResume) {
                super.onRelease(isResume);
                if (!isResume) {
                    mIvBg.setVisibility(Component.VISIBLE);
                }
            }

            @Override
            public void onEndExit() {
                super.onEndExit();
                if (animalListener != null) {
                    animalListener.animalEnd();
                }
                if (videoPlayerPlugin != null)
                    videoPlayerPlugin.release();
            }

            @Override
            public void onEndEnter() {
                super.onEndEnter();
            }

            @Override
            public void onStartExit(boolean outOfBound) {
                super.onStartExit(outOfBound);
                Log.i("MeiVideoDragFragment.onStartExit([outOfBound]):217");
            }

            @Override
            public void onEndResume() {
                super.onEndResume();
                Log.i("MeiVideoDragFragment.onEndResume([]):224");
                titleShow.setVisibility(Component.VISIBLE);
                mIvClose.setVisibility(Component.VISIBLE);
            }
        });
    }

    public void play() {
        if (videoPlayerPlugin == null || surfaceProvider == null || surface == null) {
            Log.i("MeiVideoDragFragment.play([]):225   play error!!!");
            return;
        }
        String WEB_VIDEO_PATH = getFractionAbility().getString(ResourceTable.String_WEB_VIDEO_PATH);
        AVDescription bean =
                new AVDescription.Builder()
                        .setTitle("web_video_01")
                        .setIMediaUri(Uri.parse(WEB_VIDEO_PATH))
                        .setMediaId(WEB_VIDEO_PATH)
                        .build();
        videoPlayerPlugin.startPlay(new AVElement(bean, AVElement.AVELEMENT_FLAG_PLAYABLE), surface);
    }

    private void playVideo() {
        if (titleShow != null && mIvClose != null) {
            titleShow.setVisibility(Component.VISIBLE);
            mIvClose.setVisibility(Component.VISIBLE);
        }
        if (!isCreateSuface) {
            if (getFractionAbility() == null) {
                Log.i("MeiVideoDragFragment.playVideo([]):249   getFractionAbility():null");
                return;
            }
            if (videoPlayerPlugin == null || surface == null) {
                isCreateSuface = true;
                Log.i("MeiVideoDragFragment.playVideo([]):235  videoPlayerPlugin  create " + tag);
                surfaceProvider = new SurfaceProvider(getFractionAbility());
                surfaceProvider.getSurfaceOps().get().addCallback(new SurfaceCallBack());
                surfaceProvider.pinToZTop(false);
                WindowManager.getInstance().getTopWindow().get().setTransparent(true);
                playVideo.addComponent(surfaceProvider);
                videoPlayerPlugin = new VideoPlayerPlugin(getApplicationContext());
            } else {
                Log.i("MeiVideoDragFragment.playVideo([]):243  videoPlayerPlugin restart  " + tag + "          " + videoPlayerPlugin);
                play();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (videoPlayerPlugin != null) {
            playVideo.removeComponent(surfaceProvider);
            videoPlayerPlugin.release();
            surfaceProvider = null;
            videoPlayerPlugin = null;
        }
    }

    interface AnimalListener {
        void animalEnd();
    }

    public void endInExitAnimal() {
        mDragLayout.endTransitions();
    }
}
